$(document).ready(function() {
    // 声明变量，获取变量
    const api = require("./modules/api.js");
    const location = require("./modules/location.js");
    const env = new nunjucks.Environment(new nunjucks.WebLoader('/views'));
    const table_temp = env.getTemplate("order_confirm_table.html");
    const shopCart = localStorage.getItem("shopCart") ? JSON.parse(localStorage.getItem("shopCart")) : {};
    // 计算运费总额
    let freight = 0;
    let totalPrice = 0;
    let payPrice = 0;
    let quantities = 0;
    let tradeType = "OFFLINE";
    let addressList = [];

    // 获取地址
    getAddress();

    let items = [];
    for (let i = 0; i < shopCart.items.length; i++) {
        items.push({
            productId: shopCart.items[i].itemId,
            quantity: shopCart.items[i].quantity
        })
    };
    // 表单数据
    let form = {
        itemsStr: JSON.stringify(items),
        type: shopCart.type,
        payPrice: payPrice,
        province: "",
        city: "",
        area: "",
        address: "",
        userName: "",
        userPhone: "",
        tradeType: tradeType,
        remarks: "",
        freight: freight
    };


    // 添加过滤器
    // 计算单价
    env.addFilter("computeUnitPrice", (item) => {
        let quantity = item.quantity;
        let price = "";
        if (shopCart.type == "TP") {
            price = item.product.tpPrice;
        } else if (shopCart.type == "PF") {
            price = item.product.pfPrice;
        };
        let discountsConfig = item.product.discountsConfig;
        for (let i = 0; i < discountsConfig.length; i++) {
            if (quantity <= discountsConfig[i].max) {
                return (price * discountsConfig[i].discount).toFixed(2);
            }else if(quantity >= discountsConfig[discountsConfig.length - 1].max){
                return (price * discountsConfig[discountsConfig.length - 1].discount).toFixed(2);
            };
        };

    });
    // 计算总价
    env.addFilter("computerTotalPrice", (item) => {
        let quantity = item.quantity;
        let price = "";
        if (shopCart.type == "TP") {
            price = item.product.tpPrice;
        } else if (shopCart.type == "PF") {
            price = item.product.pfPrice;
        };
        //let tpPrice = item.product.tpPrice;
        let discountsConfig = item.product.discountsConfig;
        for (let i = 0; i < discountsConfig.length; i++) {
            if (quantity <= discountsConfig[i].max) {
                return (price * discountsConfig[i].discount * quantity).toFixed(2);
            }else if(quantity >= discountsConfig[discountsConfig.length - 1].max){
                return (price * discountsConfig[discountsConfig.length - 1].discount * quantity).toFixed(2);
            };
        };
    });
    // 计算运费
    env.addFilter("computeFreight", (item) => {
        let quantity = item.quantity;
        let unitFreight = item.product.unitFreight;
        return quantity * unitFreight;
    });
    // 保留两位小数
    env.addFilter("toFixed", (number) => {
        return mumber.toFixed(2);
    });
    env.addFilter("formatType", (type)=>{
        switch(type){
            case "TP":
                return "贴牌";
            case "PF":
                return "批发";
            default:
                return type
        };
    });
    



    for (let i = 0; i < shopCart.items.length; i++) {
        let quantity = shopCart.items[i].quantity;
        let unitFreight = shopCart.items[i].product.unitFreight;
        //let tpPrice = shopCart.items[i].product.tpPrice;
        let price = "";
        if (shopCart.type == "TP") {
            price = shopCart.items[i].product.tpPrice;
        } else if (shopCart.type == "PF") {
            price = shopCart.items[i].product.pfPrice
        };

        let discountsConfig = shopCart.items[i].product.discountsConfig;
        freight += (quantity * unitFreight);
        quantities += parseInt(quantity);

        for (let j = 0; j < discountsConfig.length; j++) {
            if (quantity <= discountsConfig[j].max) {
                totalPrice += discountsConfig[j].discount * price * quantity;
                break;
            }else if(quantity >= discountsConfig[discountsConfig.length - 1].max){
                totalPrice += discountsConfig[discountsConfig.length - 1].discount * price * quantity;
                break;
            };
        };
    };
    totalPrice = totalPrice.toFixed(2);
    freight = freight.toFixed(2);
    form.payPrice = (parseFloat(freight) + parseFloat(totalPrice)).toFixed(2);


    table_temp.render(shopCart, function(err, str) {
        $(".table").append(str);
        $(".freight").text(freight);
        $(".totalPrice").text(totalPrice);
        $(".payPrice").text(form.payPrice);
        $(".quantities").text(quantities);
    });


    console.log(shopCart);


    // 获取省份
    getProvinces();

    function getProvinces() {
        location.getProvinces().then(res => {
            console.log(res);
            if (res.code == "0") {
                res.result.map(item => {
                    $("#province").append(`<option value=${item}>${item}</option>`)
                });
            };
        });
    };

    function getCities() {
        let province = $("#province").val();
        $("#city").empty();
        $("#city").append("<option value=''>市</option>");
        location.getCities({ province }).then(res => {
            console.log(res);
            if (res.code == "0") {
                res.result.map(item => {
                    $("#city").append(`<option value=${item}>${item}</option>`)
                });
            };
        });
    };

    function getAreas() {
        let province = $("#province").val();
        let city = $("#city").val();
        $("#area").empty();
        $("#area").append("<option value=''>区</option>");
        location.getAreas({ province, city }).then(res => {
            if (res.code == "0") {
                res.result.map(item => {
                    $("#area").append(`<option value=${item}>${item}</option>`);
                });
            };
        });
    };

    // 监测省份变化
    $("#province").change(function() {
        getCities();
        getAreas();
        location_validator();
    });
    // 监测市变化
    $("#city").change(function() {
        getAreas();
        location_validator();
    });

    // 监测地区变化
    $("#area").change(function() {
        location_validator();
    });


    // 添加地址校验
    $("#userName").bind("input property", function() {
        userName_validator();
    });
    $("#userPhone").bind("input property", function() {
        userPhone_validator();
    });
    $("#address").bind("input property", function() {
        address_validator();
    });

    function userName_validator() {
        let userName = $("#userName").val();
        if (userName) {
            $("#userName").nextAll(".error-message").fadeOut();
            return true;
        } else {
            $("#userName").nextAll(".error-message").text("请填写收货人").fadeIn();
            return false;
        };
    };

    function userPhone_validator() {
        let userPhone = $("#userPhone").val();
        if (!userPhone) {
            $("#userPhone").nextAll(".error-message").text("请填写联系方式").fadeIn();
            return false;
        };
        if (!/(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/.test(userPhone)) {
            $("#userPhone").nextAll(".error-message").text("请填写合法的手机号").fadeIn();
            return false;
        };
        $("#userPhone").nextAll(".error-message").fadeOut();
        return true;
    };

    function address_validator() {
        let address = $("#address").val();
        if (!address) {
            $("#address").nextAll(".error-message").text("请填写详细地址").fadeIn();
            return false;
        };
        $("#address").nextAll(".error-message").fadeOut();
        return true;
    };

    function location_validator() {
        let province = $("#province").val();
        let city = $("#city").val();
        let area = $("#area").val();
        if (!province) {
            $("#province").nextAll(".error-message").text("请选择所在省份").fadeIn();
            return false;
        };
        if (!city) {
            $("#province").nextAll(".error-message").text("请选择所在城市").fadeIn();
            return false;
        }
        if (!area) {
            $("#province").nextAll(".error-message").text("请选择所在地区").fadeIn();
            return false;
        };
        $("#province").nextAll(".error-message").text("请选择所在地区").fadeOut();
        return true;
    };

    function on_submit_validator() {
        return [
            userName_validator(),
            userPhone_validator(),
            address_validator(),
            location_validator()
        ].every(item => item);
    };

    handleAddressChange();
    // 监测选择地址变化
    function handleAddressChange() {
        $("input[name=address]").off();
        $("input[name=address]").change(function() {
            if ($(this).val() == "new") {
                $(".add-address-form").slideDown();
            } else {
                address_selected();

                $(".add-address-form").slideUp();
            };
        });
    };


    // 点击确认收货地址
    $("#confirm-address").click(function() {
        if (on_submit_validator()) {
            let name = $("#userName").val();
            let phone = $("#userPhone").val();
            let province = $("#province").val();
            let city = $("#city").val();
            let area = $("#area").val();
            let address = $("#address").val();
            api.address_add({ name, phone, province, city, area, address }).then(res => {
                if (res.code == "0") {
                    getAddress();
                    emptyAddress();
                    $(".add-address-form").slideUp();
                };
            });
        }
    });

    function address_selected() {
        let addressId = $("input[name=address]:checked").val();
        for (let i = 0; i < addressList.length; i++) {
            if (addressList[i].id == addressId) {
                console.log(addressList[i]);
                form.province = addressList[i].province + "省";
                form.city = addressList[i].city + "市";
                form.area = addressList[i].area;
                form.address = addressList[i].address;
                form.userName = addressList[i].name;
                form.userPhone = addressList[i].phone;
            };
        };
    };

    function emptyAddress() {
        $("#userName").val("");
        $("#userPhone").val("");
        $("#province").val("");
        $("#city").val("");
        $("#address").val("");
        $("#address").val("");
    };

    // 获取收货地址
    function getAddress() {
        api.address_myList().then(res => {
            if (res.code == "0") {
                $(".address-list").empty();
                addressList = res.result.list || [];
                addressList.map((item, index) => {
                    let addressItem = `
                        <label for="" class="radio-label">
                            <input checked=${index == addressList.length - 1} value="${item.id}" checked name="address" type="radio"> ${item.city}市${item.address}-${item.name}-${item.phone} <span></span>
                        </label>`;
                    $(".address-list").append(addressItem);
                });
                handleAddressChange();
                address_selected();
            };
        });
    };

    // 切换交易类型
    $(".jiaoyileixing span").click(function() {
        $(".jiaoyileixing span").removeClass("active");
        $(this).addClass("active");
        tradeType = $(this).data()["tradetype"];
    });
    
    // 监测留言变化

    // 提交订单
    $(".submit-btn").click(function() {
        form.remarks = $("#remarks").val();
        console.log(form);
        api.order_create(form).then(res => {
            console.log(res);
            if (res.code == "0") {
                window.location.href = "/success";
            }else{
                alert("请稍后再试！");
            }
        });
    });

});